<?php

namespace app\admin\controller;

use app\admin\model\SystemUploadfile;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use think\App;
use think\facade\Db;

/**
 * Class Admin
 * @package app\admin\controller
 * @ControllerAnnotation(title="员工管理")
 */
class Users extends AdminController
{
    protected $sort = [
        'job_number' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Users();
        
        $this->assign('getGenderList', $this->model->getGenderList());

        $this->assign('getStatusList', $this->model->getStatusList());

        $this->assign('getBankList', $this->model->getBankList());

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->except(['job_number'],'post');
            $post['job_number'] = getJobNumber();
            $rule = [
                'true_name|真实姓名' =>  'require|chs',
                'phone|手机号'       =>  'require|mobile|unique:users',
                'gender|性别'        =>  'require|in:0,1',
                'age|年龄'           =>  'require|between:18,65',
                'status|状态'        =>  'require|in:0,1',
            ];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $row = $this->model->find($this->request->param($this->model->getPk()));
        $row->isEmpty() && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'true_name|真实姓名'   =>  'require|chs',
                'phone|手机号'         =>  'require|mobile',
                'gender|性别'          =>  'require|in:0,1',
                'age|年龄'             =>  'require|between:18,65',
                'base_salary|基本工资' =>  'require|float',
                'entry_date|入职日期'  =>  'require|date',
                'status|状态'          =>  'require|in:0,1',
            ];
            $this->validate($post, $rule);
            if (isset($post['head_img'])){
                $id = SystemUploadfile::where('url', $post['head_img'])->value('id');
                if (!empty($id)){
                    $post['head_img_id'] = $id;
                }
            }
            try {
                $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $this->success('保存成功');
        }
        $row->head_img = SystemUploadfile::where('id', $row['head_img_id'])->value('url');
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="设置密码")
     */
    public function password()
    {
        $pk = $this->request->param($this->model->getPk());
        $row = $this->model->find($pk);
        $row->isEmpty() && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }
            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFileds)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order($this->sort)
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
}